# coding:utf-8
import uuid
from pathlib import Path
from typing import Union, Any
from PyQt5.QtWidgets import QFrame, QLabel, QToolButton, QHBoxLayout, QVBoxLayout, QApplication, QSpacerItem, \
    QSizePolicy, QListWidget, QListWidgetItem, QWidget, QAbstractItemView
from PyQt5.QtCore import Qt, pyqtSignal, QSize, pyqtProperty, QThread
from PyQt5.QtGui import QResizeEvent, QIcon, QPixmap, QPainter
from common import MaskDialogBase, IconWidget
from tools import CreateThumbnail, getStyleSheetFromFile
from model import Thumbnail
from config import imagesPath, Session
import res.res_rc


class ImageThumbnailThread(QThread):
    saveFile = pyqtSignal(str, str)

    def __init__(self, parent=None):
        super().__init__(parent)

    def run(self):
        session = Session()

        for file in self.fileNames:
            if Path(file).suffix not in ['.png', '.jpg', '.jpeg']:
                self.saveFile.emit(file, file)
                continue
            thumbnail = session.query(Thumbnail).filter(Thumbnail.original_path == file).scalar()

            if thumbnail is not None:
                thumbnail_path = thumbnail.thumbnail_path
                if not Path(thumbnail_path).is_file():
                    uid = str(uuid.uuid4())
                    thumbnail_path = str(imagesPath / f"{uid}.png")
                    CreateThumbnail(file, thumbnail_path)
                    thumbnail.thumbnail_path = thumbnail_path
                else:
                    thumbnail_path = thumbnail.thumbnail_path
            else:
                uid = str(uuid.uuid4())
                thumbnail_path = str(imagesPath / f"{uid}.png")
                CreateThumbnail(file, thumbnail_path)
                session.add(Thumbnail(id=uid, original_path=file, thumbnail_path=thumbnail_path))
            self.saveFile.emit(file, thumbnail_path)
        session.commit()

    def setValue(self, fileNames: list[str]):
        self.fileNames = fileNames


class TopToolsView(QFrame):
    rotationed = pyqtSignal(bool)
    deleted = pyqtSignal(bool)
    setWallpapered = pyqtSignal(bool)
    saveAsed = pyqtSignal(bool)
    detailed = pyqtSignal(bool)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setFixedHeight(50)

        self.titleLabel = QLabel()
        self.rotationButton = QToolButton()
        self.deleteButton = QToolButton()
        self.setWallpaperButton = QToolButton()
        self.saveAsButton = QToolButton()
        self.detailsButton = QToolButton()

        self.__initLayout()
        self.__defaultText()

        self.rotationButton.clicked.connect(self.rotationed.emit)
        self.deleteButton.clicked.connect(self.deleted.emit)
        self.setWallpaperButton.clicked.connect(self.setWallpapered.emit)
        self.saveAsButton.clicked.connect(self.saveAsed.emit)
        self.detailsButton.clicked.connect(self.detailed.emit)

    def __initLayout(self):
        self.hBoxLayout = QHBoxLayout(self)
        self.hBoxLayout.setContentsMargins(0, 0, 0, 0)
        self.hBoxLayout.setSpacing(2)

        self.titleLabel.setFixedHeight(40)
        self.rotationButton.setFixedSize(40, 40)
        self.deleteButton.setFixedSize(40, 40)
        self.setWallpaperButton.setFixedSize(40, 40)
        self.saveAsButton.setFixedSize(40, 40)
        self.detailsButton.setFixedSize(40, 40)

        self.hBoxLayout.addWidget(self.titleLabel, 0, Qt.AlignLeft)
        self.hBoxLayout.addWidget(self.rotationButton)
        self.hBoxLayout.addWidget(self.deleteButton)
        self.hBoxLayout.addWidget(self.setWallpaperButton)
        self.hBoxLayout.addWidget(self.saveAsButton)
        self.hBoxLayout.addWidget(self.detailsButton)

    def __defaultText(self):
        self.titleLabel.setText('图片文件')
        self.rotationButton.setText(self.tr('旋转图片'))
        self.rotationButton.setToolTip(self.tr('旋转图片'))
        self.deleteButton.setText(self.tr('删除'))
        self.deleteButton.setToolTip(self.tr('删除'))
        self.setWallpaperButton.setText(self.tr('设置为壁纸'))
        self.setWallpaperButton.setToolTip(self.tr('设置为壁纸'))
        self.saveAsButton.setText(self.tr('另存为'))
        self.saveAsButton.setToolTip(self.tr('另存为'))
        self.detailsButton.setText(self.tr('详情'))
        self.detailsButton.setToolTip(self.tr('详情'))
        self.__initIcon()

    def __initIcon(self):
        self.rotationButton.setIcon(QIcon(':/svg/svg/Rotate_black.svg'))
        self.saveAsButton.setIcon(QIcon(':/svg/svg/SaveCopy_black.svg'))
        self.deleteButton.setIcon(QIcon(':/svg/svg/Delete_black.svg'))
        self.setWallpaperButton.setIcon(QIcon(':/svg/svg/ImageExport_black.svg'))
        self.detailsButton.setIcon(QIcon(':/svg/svg/Info_black.svg'))

    def setText(self, text: str):
        self.titleLabel.setText(text)
        self.update()

    def text(self):
        return self.titleLabel.text()


class BottomToolsView(QFrame):
    added = pyqtSignal(bool)
    menued = pyqtSignal(bool)
    enlarged = pyqtSignal(bool)
    shrinked = pyqtSignal(bool)
    scaleToFited = pyqtSignal(bool)
    actualed = pyqtSignal(bool)
    fullScreened = pyqtSignal(bool)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setFixedHeight(50)
        self.addButton = QToolButton()
        self.menuButton = QToolButton()  # 菜单按钮
        self.enlargeButton = QToolButton()  # 放大按钮
        self.shrinkButton = QToolButton()  # 缩小按钮
        self.scaleToFitButton = QToolButton()  # 缩放以适应
        self.actualButton = QToolButton()  # 缩放到实际大小
        self.fullScreenButton = QToolButton()  # 全屏按钮
        self.__initLayout()

        self.addButton.clicked.connect(self.added.emit)
        self.menuButton.clicked.connect(self.menued.emit)
        self.enlargeButton.clicked.connect(self.enlarged.emit)
        self.shrinkButton.clicked.connect(self.shrinked.emit)
        self.scaleToFitButton.clicked.connect(self.scaleToFited.emit)
        self.actualButton.clicked.connect(self.actualed.emit)
        self.fullScreenButton.clicked.connect(self.fullScreened.emit)

    def __initLayout(self):
        self.hBoxLayout = QHBoxLayout(self)
        self.hBoxLayout.setContentsMargins(0, 0, 0, 0)
        self.hBoxLayout.setSpacing(2)
        self.hBoxLayout.setAlignment(Qt.AlignRight)

        self.addButton.setFixedSize(40, 40)
        self.menuButton.setFixedSize(40, 40)
        self.enlargeButton.setFixedSize(40, 40)
        self.shrinkButton.setFixedSize(40, 40)
        self.scaleToFitButton.setFixedSize(40, 40)
        self.actualButton.setFixedSize(40, 40)
        self.fullScreenButton.setFixedSize(40, 40)

        self.hBoxLayout.addWidget(self.addButton)
        self.hBoxLayout.addWidget(self.menuButton)
        self.hBoxLayout.addWidget(self.enlargeButton)
        self.hBoxLayout.addWidget(self.shrinkButton)
        self.hBoxLayout.addWidget(self.scaleToFitButton)
        self.hBoxLayout.addWidget(self.actualButton)
        self.hBoxLayout.addWidget(self.fullScreenButton)

        self.__defaultText()

    def __defaultText(self):
        self.addButton.setText('添加文件')
        self.addButton.setToolTip('添加文件')
        self.menuButton.setText('图片列表')
        self.menuButton.setToolTip('图片列表')
        self.enlargeButton.setText('放大按钮')
        self.enlargeButton.setToolTip('放大按钮')
        self.shrinkButton.setText('缩小按钮')
        self.shrinkButton.setToolTip('缩小按钮')
        self.scaleToFitButton.setText('缩放以适应')
        self.scaleToFitButton.setToolTip('缩放以适应')
        self.actualButton.setText('缩放到实际大小')
        self.actualButton.setToolTip('缩放到实际大小')
        self.fullScreenButton.setText('全屏按钮')
        self.fullScreenButton.setToolTip('全屏按钮')
        self.__initIcon()

    def __initIcon(self):
        self.addButton.setIcon(QIcon(':/svg/svg/AddTo_black.svg'))
        self.menuButton.setIcon(QIcon(':/svg/svg/Menu_black.svg'))
        self.enlargeButton.setIcon(QIcon(':/svg/svg/ZoomIn_black.svg'))
        self.shrinkButton.setIcon(QIcon(':/svg/svg/ZoomOut_black.svg'))
        self.scaleToFitButton.setIcon(QIcon(':/svg/svg/FitPage_black.svg'))
        self.actualButton.setIcon(QIcon(':/svg/svg/1_1.svg'))
        self.fullScreenButton.setIcon(QIcon(':/svg/svg/FullScreen_black.svg'))


class PictureDetailsDialog(MaskDialogBase):
    """ 图片详细信息 """

    def __init__(self, parent=None):
        super().__init__(parent)

        self.closeButton = QToolButton(self.widget)
        self.titleLabel = QLabel('详细信息', self)
        self.titleLabel.setObjectName('titleLabel')
        self.nameLabel = QLabel('图片名称：', self)
        self.typeLabel = QLabel('图片类型：', self)
        self.sizeLabel = QLabel('图片大小：', self)
        self.sizeLabel_2 = QLabel('图片尺寸：', self)
        self.posLabel = QLabel('图片位置：', self)

        self.__initWidget()

    def __initWidget(self):
        self._hBoxLayout.setContentsMargins(100, 100, 100, 100)
        self.widget.setObjectName("pictureDetailsDialog")
        self.VBoxLayout = QVBoxLayout(self.widget)
        self.VBoxLayout.setContentsMargins(100, 100, 100, 100)
        self.VBoxLayout.setSpacing(10)

        self.closeButton.setFixedSize(40, 40)
        self.closeButton.setIcon(QIcon(':/svg/svg/Close_black.svg'))
        self.closeButton.clicked.connect(self.close)

        self.VBoxLayout.addWidget(self.titleLabel, 0, Qt.AlignHCenter | Qt.AlignTop)
        self.VBoxLayout.addWidget(self.nameLabel)
        self.VBoxLayout.addWidget(self.typeLabel)
        self.VBoxLayout.addWidget(self.sizeLabel)
        self.VBoxLayout.addWidget(self.sizeLabel_2)
        self.VBoxLayout.addWidget(self.posLabel)
        spacerItem = QSpacerItem(100, 100, QSizePolicy.Minimum, QSizePolicy.Minimum)
        self.VBoxLayout.addSpacerItem(spacerItem)

    def resizeEvent(self, e):
        self.closeButton.move(self.widget.width() - 40, 0)
        super().resizeEvent(e)

    def setFile(self, file: Union[str | Path]):
        path = Path(file)
        pixmap = QPixmap(file)
        self.nameLabel.setText('图片名称：' + path.name)
        self.typeLabel.setText('图片类型：' + path.suffix)
        self.sizeLabel.setText('图片大小：' + str(round(path.stat().st_size / 1024 / 1024, 3)) + 'M')
        self.sizeLabel_2.setText('图片尺寸：' + f'{pixmap.width()} X {pixmap.height()}')
        self.posLabel.setText('图片位置：' + file)
        self.update()


class ImagePager(QListWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self._imagePos = 0

        self.setFixedHeight(98)
        self.setSpacing(1)
        self.setIconSize(QSize(145, 90))
        self.setMouseTracking(True)
        self.setUniformItemSizes(True)
        self.setMovement(QListWidget.Movement.Static)
        self.setVerticalScrollMode(self.ScrollMode.ScrollPerPixel)
        self.setHorizontalScrollMode(self.ScrollMode.ScrollPerPixel)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        self.setFlow(self.LeftToRight)

        self.imageThread = ImageThumbnailThread(self)
        self.imageThread.saveFile.connect(self.addImage)

        qss = getStyleSheetFromFile(':/qss/qss/list.css')
        self.setStyleSheet(qss)

    def addImage(self, file, thumbnail_path):
        widget = IconWidget(thumbnail_path)
        widget.setFixedSize(QSize(146, 86))
        item = QListWidgetItem()
        item.setToolTip(file)
        item.setSizeHint(QSize(150, 90))
        self.addItem(item)
        self.setItemWidget(item, widget)

        self.setCurrentRow(self._imagePos)
        self.scrollToItem(self.item(self._imagePos), QAbstractItemView.PositionAtCenter)
        self.scrollToItem(self.currentItem(), QAbstractItemView.PositionAtCenter)

    def addImages(self, files: list):
        self.imageThread.setValue(files)
        self.imageThread.start()

    def setImagePos(self, imagePos: int):
        self._imagePos = imagePos

    def imagePos(self):
        return self._imagePos
